package com.neutech.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/*")
public class AuthServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path= req.getPathInfo();
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if ("/login".equals(path)){
            if ("user".equals(username) && "pass".equals(password)){
                HttpSession session = req.getSession();
                session.setAttribute("user",username);
                resp.getWriter().println("登入成功.Session ID:"+session.getId());
            } else if ("/logout".equals(path)) {
                HttpSession session = req.getSession(false);
                if (session != null){
                    session.invalidate();
                    resp.getWriter().println("退出登录");
                }
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getPathInfo();
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        if ("/checkStatus".equals(path)){
            HttpSession session = req.getSession(false);
            if (session != null){
                resp.getWriter().println("用户已经登入.Session ID:" + session.getId() );
            }else {
                resp.getWriter().println("用户登录.");
            }
        }
    }
}
